unit lsAudioPlayer;

interface

uses
  Controls, XMLIntf, lsComponent, MPlayer, Classes, ExtCtrls;

type
  TlsAudioPlayer = class(TlsComponent)
  private
   FPlayer: TMediaPlayer;
   FFiles: TStringList;
   FDelay: Integer;
   FFileName: string;
   FPlayTimer: TTimer;
   FIndex: Integer;
   procedure Playlist(AIndex, ADelay: Integer);
   procedure ResponsePlayer(Sender: TObject);
   procedure ResponsePlayTimer(Sender: TObject);
  protected
   procedure innerDoAction(AAction: String); override;
  public
    constructor Create(AParent: TWinControl;AlsConfig: IXMLNode);override;
    destructor  Destroy;override;
    procedure SetProperty(ANode: IXMLNode);override;
  end;

implementation

uses
  CommonUtils, SysUtils, Dialogs;

{ TlsAudioPlayer }

constructor TlsAudioPlayer.Create(AParent: TWinControl;AlsConfig: IXMLNode);
begin
  inherited;

  FPlayTimer := TTimer.Create(nil);
  FPlayTimer.Enabled := False;
  FPlayer:=TMediaPlayer.Create(nil);
  FPlayer.Parent := AParent;
  FPlayer.Visible := False;
  FFiles := TStringList.Create;
  FPlayer.OnNotify := ResponsePlayer;
end;

destructor TlsAudioPlayer.Destroy;
begin
  FreeAndNil(FPlayTimer);
  FreeAndNil(FFiles);
  FPlayer.Free;

  inherited;
end;

procedure TlsAudioPlayer.InnerDoAction(AAction: String);
begin
  inherited;
  if AAction='play' then
  begin
    FPlayer.FileName := FFileName;
    FPlayer.Open;
    FPlayer.Play;
  end
  else if AAction = 'playlist' then
    Playlist(0, 0)
  else if (AAction='stop') and (FPlayer.Mode = mpPlaying) then
  begin
    FPlayer.Stop;
    DoEventByType('stop');
  end;
end;

procedure TlsAudioPlayer.Playlist(AIndex, ADelay: Integer);
begin
  FIndex := AIndex;
  if ADelay > 0 then
  begin
    FPlayTimer.Interval := ADelay;
    FPlayTimer.OnTimer := ResponsePlayTimer;
    FPlayTimer.Enabled := True;
  end
  else
    ResponsePlayTimer(nil);
end;

procedure TlsAudioPlayer.ResponsePlayer(Sender: TObject);
begin
  Inc(FIndex);
  if FIndex < FFiles.Count then
    Playlist(FIndex, FDelay)
  else begin
    FPlayer.Close;
    DoEventByType('stop');
  end;
end;

procedure TlsAudioPlayer.ResponsePlayTimer(Sender: TObject);
begin
  FPlayTimer.Enabled := False;
  FPlayer.Close;
  FPlayer.FileName := FFiles[FIndex];
  FPlayer.Open;
  FPlayer.Play;
end;

procedure TlsAudioPlayer.SetProperty(ANode: IXMLNode);
var
  I: Integer;
begin
  FFileName := PathOfTrain+ GetChildNodeValue(ANode, 'filename');
  FDelay := StrToIntDef(GetChildNodeValue(ANode, 'delay'), 100);
  FFiles.Clear;
  GetChildNodeStrings(ANode, 'strings', FFiles);
  for I := 0 to FFiles.Count - 1 do
    FFiles[I] := PathOfTrain + FFiles[I];
end;

end.
